# encoding: utf-8
from flask_script import Manager
from app import create_app
from flask_migrate import MigrateCommand, Migrate
from exts import db
from utils.captcha import Captcha

# 导入模型
from apps.cms import models as cms_models
from apps.front import models as front_models

CMSUser = cms_models.CMSUser
CMSRole = cms_models.CMSRole
CMSPermission = cms_models.CMSPermission
FrontUser = front_models.FrontUser



app = create_app()
manager = Manager(app)

# 绑定migrate
Migrate(app, db)
manager.add_command("db", MigrateCommand)

@manager.option("-u", "--username", dest="username")
@manager.option("-p", "--password", dest="password")
@manager.option("-e", "--email", dest="email")
def create_cms_user(username, password, email):
    user = CMSUser(username, password, email)
    db.session.add(user)
    db.session.commit()

@manager.command
def create_role():
    # 1.访问者
    visitor = CMSRole(name="访问者", desc="只能访问，不能修改")
    visitor.permissions = CMSPermission.VISITOR

    # 2.运营角色(可以修改个人信息、可以管理前台用户、可以管理帖子、可以管理评论)
    operator = CMSRole(name="运营", desc="管理帖子、管理评论、管理前台用户")
    operator.permissions = CMSPermission.VISITOR | CMSPermission.POSTER | CMSPermission.COMMENTER | CMSPermission.FRONTUSER

    # 3.管理员(拥有本系统绝大部分权限)
    admin = CMSRole(name="管理员", desc="拥有本系统全部权限")
    admin.permissions = CMSPermission.VISITOR | CMSPermission.POSTER | CMSPermission.COMMENTER | CMSPermission.FRONTUSER | CMSPermission.BOARDER | CMSPermission.CMSUSER

    # 4. 开发者
    developer = CMSRole(name="开发者", desc="开发人员专用")
    developer.permissions = CMSPermission.ALL_PERMISSION

    db.session.add_all([visitor, operator, admin, developer])
    db.session.commit()


@manager.command
def test_permission():
    user = CMSUser.query.first()
    if user.has_permission(CMSPermission.VISITOR):
        print("这个用户有访问者权限")
    else:
        print("这个用户没有访问者权限")

    print(user.is_developer)
    if user.is_developer:
        print("这个用户是开发者")
    else:
        print("这个用户不是开发者")


@manager.option("-e", "--email", dest="email")
@manager.option("-n", "--name", dest="name")
def add_user_to_role(email, name):
    user = CMSUser.query.filter_by(email=email).first()
    role = CMSRole.query.filter_by(name=name).first()

    if user:
        if role:
            role.users.append(user)
            db.session.commit()
        else:
            print("角色不存在！")
    else:
        print("邮箱不存在！")

@manager.command
def test_front_user():
    user = FrontUser(phone="18058742792", username="liuwenchao", password="123456")
    print(user.password)

    db.session.add(user)
    db.session.commit()

@manager.command
def generate_random_font():
    font = Captcha._generate_random_font()
    print(font)

@manager.command
def generate_random_text():
    text = Captcha.generate_random_text(6)
    print(text)

@manager.command
def generate_graph_captcha():
    Captcha.generate_graph_captcha()

# 添加用户
if __name__ == "__main__":
    manager.run()